const bcrypt = require('bcryptjs')
const {getUserInfo} = require("../service/user.service");
const { userFormatError, userAlreadyExited, userRegisterError, userDoesNotExist, userLoginError, invalidPassword } = require('../consitan/err.type')
const userValidator = async (ctx, next) => {
    const { userName, passWord } = ctx.request.body
    if(!userName || !passWord) {
        console.error('用户名或密码不能为空', ctx.request.body)
        ctx.app.emit('error', userFormatError, ctx)
        return
    }
    await next()
}
const verifyUser = async (ctx, next) => {
    const { userName } = ctx.request.body
    try {
        const res = await getUserInfo({userName})
        if(res) {
            console.error('用户名已存在', {userName})
            ctx.app.emit('error', userAlreadyExited, ctx)
            return
        }
    } catch (err) {
        console.error('获取用户信息错误', err)
        ctx.app.emit('error', userRegisterError, ctx)
        return
    }
    await next()
}
const bcryptPassword = async (ctx, next) => {
    const { passWord } = ctx.request.body
    const salt = bcrypt.genSaltSync(10);
    ctx.request.body.passWord = bcrypt.hashSync(passWord, salt);
    await next()
}
const verifyLogin = async (ctx, next) => {
    const { userName, passWord } = ctx.request.body
    try {
        const res = await getUserInfo({ userName })
        if(!res) {
            console.error('用户不存在', { userName })
            ctx.app.emit('error', userDoesNotExist, ctx)
            return
        }
        // 密码是否匹配
        if(!bcrypt.compareSync(passWord, res.passWord)) {
            ctx.app.emit('error', invalidPassword, ctx)
            return
        }
    } catch (err) {
        console.error(err)
        return ctx.app.emit('error', userLoginError, ctx)
    }
    await next()
}
module.exports = {
    userValidator,
    verifyUser,
    bcryptPassword,
    verifyLogin
}